import datetime
import json
import logging
import os.path

from flask import Flask, request
from jiyan import Geetest

app = Flask(__name__)
filename = os.path.realpath(__file__)
appPath = os.path.dirname(filename)
filename = f"{appPath}/{datetime.date.today()}.log"
if os.path.isfile(filename):
    os.remove(filename)

logging.basicConfig(filename=filename, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


@app.route('/get-token', methods=['GET'])
def get_token():
    gt = request.args.get('gt')
    challenge = request.args.get('challenge')
    if gt is None or challenge is None:
        return json.dumps({'success': False, 'msg': 'require data params'})
    gee = Geetest(gt, challenge)
    gee.get_script()
    gee.get_c_s()
    isNext, validate = gee.get_type()
    if isNext:
        validate = gee.get_bg()
        if type(validate) != str:
            return json.dumps({'success': False, 'msg': 'failed', 'data': validate})

    return json.dumps({'success': True, 'msg': 'success', 'data': {
        'validate': validate,
    }})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005, debug=True)
